<template>
  <!-- 上架作业 -->
  <div id="PackingMarking">
    <root name="PackingMarking">
      <SafeHeader
        v-bind="{
          title: '装箱上架',
          isBack: true,
          fixedTop: true,
        }"
      />
      <div style="padding-top:60px">
        <v-container class="head">
          <v-card outlined class="py-4">
            <v-row class="ma-0 mb-4">
              <v-col class="py-1">
                <v-text-field
                  id="scanInfo"
                  :prepend-icon="mdiCreditCardScan"
                  clearable
                  autofocus
                  class="my-0 inputPlaceholder"
                  @keydown.13="scanGenerateCode"
                  dense
                  hide-details
                  v-model="scanInfo"
                  placeholder="请扫描收货单号"
                ></v-text-field>
              </v-col>
            </v-row>
            <v-row class="ma-0 mb-4">
              <v-col class="py-1">
                <v-text-field
                  id="barBoxCode"
                  :prepend-icon="mdiCreditCardScan"
                  clearable
                  class="my-0 inputPlaceholder"
                  @keydown.13="scanBoxCode"
                  dense
                  hide-details
                  v-model="barBoxCode"
                  placeholder="请扫描托盘码"
                ></v-text-field>
              </v-col>
            </v-row>
            <v-row class="ma-0 mb-4">
              <v-col class="py-1">
                <v-text-field
                  id="targetWorkCellCode"
                  :prepend-icon="mdiCreditCardScan"
                  clearable
                  class="my-0 inputPlaceholder"
                  @keydown.13="scanCellCode"
                  dense
                  hide-details
                  v-model="targetWorkCellCode"
                  placeholder="请扫描库位码"
                ></v-text-field>
              </v-col>
            </v-row>
            <v-checkbox v-model="isAllChecked" label="全选" @change="handleAllCheck"></v-checkbox>
          </v-card>
        </v-container>
        <v-container class="list-container">
          <div class="list-box">
            <v-card outlined class="py-4 top-list" v-for="(item, index) in taskList" :key="index">
              <div>物料编码：{{item.itemCode}}</div>
              <div>物料名称：{{item.itemName}}</div>
              <div>可装箱数量：{{item.qty}}</div>
              <div>
                数量：
                <input v-model="item.pcs" @input="inpHandle(item)" type="number" />
              </div>
              <div>
                履约号：
                <input v-model="item.agreementNo"  type="text" />
              </div>
              <v-checkbox v-model="item.flag"></v-checkbox>
            </v-card>
          </div>
          <v-btn
            color="#627AEC"
            dark
            :disabled="isOK"
            style="width: 60%; margin-top: 10px; border-radius: 12px;margin-left: 20%"
            @click="save"
          >保存</v-btn>
        </v-container>

        <v-container class="task_list mb-15 white">
          <v-row>
            <v-col cols="12" class="card-title" style="padding-bottom: 8px; padding-top: 8px">装箱列表</v-col>
          </v-row>
          <v-divider class="mb-2"></v-divider>
          <div v-if="ctInfoList[0]">
            <v-container v-for="(item, index) in ctInfoList" :key="index">
              <v-row>
                <v-col cols="12" class="pa-0 pb-2">
                  <v-card outlined style="background-color: #f2f3f5">
                    <v-card-subtitle>
                      <v-row class="pa-0 d-flex flex-row justify-space-between wms-v-row">
                        <v-col cols="4" class="py-1 card-lable">容器号</v-col>
                        <v-col class="py-1 card-value">
                          {{
                          item.boxCode
                          }}
                        </v-col>
                      </v-row>
                      <v-row class="pa-0 d-flex flex-row justify-space-between wms-v-row">
                        <v-col cols="4" class="py-1 card-lable px-2">物料编码</v-col>
                        <v-col class="py-1 card-value px-2">
                          {{
                          item.itemCode
                          }}
                        </v-col>
                      </v-row>
                      <v-row class="pa-0 d-flex flex-row justify-space-between wms-v-row">
                        <v-col cols="4" class="py-1 card-lable">物料名称</v-col>
                        <v-col class="py-1 card-value">
                          {{
                          item.itemName
                          }}
                        </v-col>
                      </v-row>
                      <v-row class="pa-0 d-flex flex-row justify-space-between wms-v-row">
                        <v-col cols="4" class="py-1 card-lable">数量</v-col>
                        <v-col class="py-1 card-value">{{ item.qty }}</v-col>
                      </v-row>
                    </v-card-subtitle>
                  </v-card>
                </v-col>
              </v-row>
            </v-container>
          </div>
          <v-row v-else>
            <v-col cols="12" class="text-center">暂无数据</v-col>
          </v-row>
        </v-container>

        <div v-show="hidshow" class="footer">
          <v-bottom-navigation>
            <v-row class="ma-0 pa-2">
              <v-col cols="4" class="pa-4 d-flex align-center" style="font-size: 15px">
                合计：
                <span style="color: #f8a73c">{{ ctInfoList.length }}</span>
                <span>箱</span>
              </v-col>
              <v-col class="pa-0">
                <v-btn block color="#193690" dark style="height: 100%; border-radius: 8px">
                  <span
                    style="color: #fff; font-size: 15px"
                    class="font-weight-bold"
                    @click="submit"
                  >提交</span>
                </v-btn>
              </v-col>
            </v-row>
          </v-bottom-navigation>
        </div>
      </div>
    </root>
    <v-overlay :value="overlay">
      <v-progress-circular indeterminate size="64"></v-progress-circular>
    </v-overlay>
  </div>
</template>

<script>
import Root from "@/components/Root.vue";
import SafeHeader from "../../components/safeHeader_wms";
import { mdiAlarmLightOffOutline, mdiCreditCardScan } from "@mdi/js";
import _ from "lodash";
import { printToJiaBo } from "@/static/print";
// import Message from "@/components/message_box_wms/index";
// import Storage from "@/utils/storage.js";
import wms from "@/utils/business_wms";
// import { apiList } from "@/static/apiList";
export default {
  name: "PackingMarking",
  components: {
    SafeHeader,
    Root
  },
  data() {
    return {
      isAllChecked: false,
      docmHeight: document.documentElement.clientHeight,
      showHeight: document.documentElement.clientHeight,
      hidshow: true,
      overlay: false,
      valid: false,
      mdiCreditCardScan: mdiCreditCardScan,
      loading: false,
      taskList: [],
      targetWorkCellCode: "",
      scanInfo: "",
      isOK: false,
      isRule: true,
      formData: {
        itemCode: "",
        batchName: "",
        boxCode: "",
        qty: 0,
        remainQty: 0 //用于校验,防止超出此数量
      },
      acceptRecordCode: "", //收货单号
      ctItemNum: "", //收货单的数据, 暂不使用
      ctNum: "1", //每次生成一个
      ctInfoList: [],
      barBoxCode: "", // 容器托盘
      barcodeList: [], //用于标签打印
      isSubmited: false //防止重复提交
    };
  },
  methods: {
    // 扫描库位编码
    scanCellCode() {
      if (!this.barBoxCode) {
        alert("请先扫描容器!");
        this.targetWorkCellCode = "";
        return false;
      }


    },
    // 收货标签扫码回车处理
    scanGenerateCode() {
      this.ctInfoList = [];
      this.isisSubmited = false;
      this.isOK = false;
      //首先判断是否有数据
      if (this.formData.itemCode) {
        alert("已存在数据");
        return false;
      }

      let scanData = this.scanInfo.split("---");
      this.acceptRecordCode = scanData[0]; // 收货单号


      wms
        .get({
          url: "/accept/records/detail/code",
          data: { code: this.acceptRecordCode }
        })
        .then(res => {
          if (res.status == 200 && res.data.code == 200) {
            // 初始化值
            let data = res.data.data;
            data.forEach(item => {
              item.flag = true;
              item.pcs = item.qty;
            });
            this.taskList = data;
            if (this.taskList.length) {
              this.isAllChecked = true;
            } else {
              this.isAllChecked = false;
            }
          } else {
            if (res.data == "") {
              alert("该收货单不存在,请扫描正确的收货单号");
            } else {
              console.log(JSON.stringify(res.data));
              alert("查询失败:" + res.data.message);
            }
          }
        });


      this.barcodeList = [];
      document.getElementById("barBoxCode").focus();
    },
    // 扫描容器托盘
    scanBoxCode() {
      console.log("容器托盘!!!!!");
      document.getElementById("targetWorkCellCode").focus();
    },
    // 输入
    inpHandle(item) {
      if (item.pcs > item.qty) {
        item.pcs = item.qty;
      } else if (!item.pcs && item.pcs == "0") {
        item.pcs = 1;
      }
    },
    // 全选
    handleAllCheck() {
      this.taskList.forEach(item => {
        item.flag = !item.flag;
      });
    },

    // 保存绑定容器的数据，放入数组
    save() {
      this.generateBoxCode();
    },
    generateBoxCode() {
      wms
        .get({ url: "/asn/masters/findCategoryId", data: { cellCode :this.targetWorkCellCode, billNo: this.scanInfo } })
        .then(res => {
          if (res.status === 200 && res.data.code === 200) {
            this.isRule = res.data.data
            console.log(res.data.data)

            // alert(1)
            let itemNames = [];
            //校验是否已经录入数据
            let filterArr = this.taskList.filter(item => {
              return item.flag;
            });

            for (let i = 0; i < this.taskList.length; i++) {

              if (this.isRule && (this.taskList[i].agreementNo === '' || this.taskList[i].agreementNo === null)) {
                alert("请录入履约号")
                return false;
              }
            }

            filterArr.forEach(menu => {
              itemNames.push(menu.itemName);
            });
            if (!this.scanInfo) {
              this.isOK = false;
              return alert("收货标签不能为空");
            } else if (!filterArr.length) {
              this.isOK = false;

              return alert("请选择装箱数据");
            } else {
              let arr = filterArr.filter(item => {
                return !item.pcs;
              });
              if (arr.length) {
                this.isOK = false;
                return alert("请输入数量");
              }
            }
            if (!this.barBoxCode) {
              this.isOK = false;
              return alert("请扫描容器托盘");
            }

            let arr = JSON.parse(JSON.stringify(filterArr));
            this.ctInfoList.push({
              acceptList: arr,
              batchName: "",
              itemName: [...new Set(itemNames)].join(","),
              boxCode: this.barBoxCode,
              itemCode: filterArr[0].itemCode,
              qty: filterArr.reduce((pre, next) => {
                return pre + Number(next.pcs);
              }, 0)
            });
            filterArr.forEach(item => {
              item.qty = item.qty - item.pcs;
              item.pcs = item.qty;
              // item.pcs = null
            });
            let stepArr = JSON.parse(JSON.stringify(this.taskList));
            stepArr.forEach(() => {
              this.taskList.forEach((v, i) => {
                if (!v.qty) {
                  this.taskList.splice(i, 1);
                }
              });
            });
            this.isOK = true;


          } else {
            console.log(JSON.stringify(res.data));
          }
        });


    },


    //提交数据
    submit() {
      //打标
      this.barcodeList = this.ctInfoList;
      // //调用打印机打印
      // for (let i = 0; i < this.barcodeList.length; i++) {agreementNo
      //   printToJiaBo(
      //     this.barcodeList[i].itemCode,
      //     this.barcodeList[i].itemName,
      //     this.barcodeList[i].batchName,
      //     this.barcodeList[i].qty,
      //     this.barcodeList[i].boxCode
      //   );
      // }

      if (this.ctInfoList.length == 0) {
        alert("没有填写数据");
        return false;
      }
      if (!this.targetWorkCellCode) {
        if (confirm("没有填写库位,是否只装箱不上架")) {
          console.log("只装箱不上架!");
        } else {
          return false;
        }
      }

      if (this.isisSubmited) {
        if (confirm("装箱数据已提交完毕,不要重复提交")) {
          // for (let i = 0; i < this.barcodeList.length; i++) {
          //   printToJiaBo(
          //     this.barcodeList[i].itemCode,
          //     this.barcodeList[i].itemName,
          //     this.barcodeList[i].batchName,
          //     this.barcodeList[i].qty,
          //     this.barcodeList[i].boxCode
          //   );
          // }
        }
      } else {
        this.overlay = true;
        let packBoxData = {
          acceptRecordCode: this.acceptRecordCode,
          list: this.ctInfoList,
          cellCode: this.targetWorkCellCode
        };
        wms
          // .post({ url: "/transfer/create/pack/box", data: packBoxData })
          .post({ url: "/transfer/batch/create/box", data: packBoxData })
          .then(res => {
            if (res.status == 200 && res.data.code == 200) {
              // console.log(JSON.stringify(res.data));
              // console.log(JSON.stringify(this.ctInfoList));
              this.overlay = false;
              this.isisSubmited = true;
              this.barcodeList = this.ctInfoList;
              alert("提交成功");
              window.location.reload();
            } else {
              console.log(JSON.stringify(res.data));
              this.overlay = false;
              alert("提交失败：" + res.data.message);
            }
          });
      }
    }
  },

  mounted() {
    window.onresize = () => {
      return (() => {
        this.showHeight = document.body.clientHeight;
      })();
    };
    // 获取传递过来的参数
    this.scanInfo = this.$root.api.api.pageParam.scanInfo;
    this.scanGenerateCode();
  },

  watch: {
    showHeight: function() {
      if (this.docmHeight > this.showHeight) {
        this.hidshow = false;
      } else {
        this.hidshow = true;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.footer {
  position: absolute;
  padding-top: 65px;
  width: 100%;
  bottom: 0;
  ::v-deep .pa-4 {
    padding: 0 !important;
  }
}
.head {
  .mb-4 {
    margin-bottom: 5px !important;
  }
  .v-input--checkbox {
    width: 68px;
    margin: 0 0 0 4px;
  }
}
.list-container {
  padding-top: 0;
  .list-box {
    height: 200px;
    overflow: auto;
  }
}
.v-input--checkbox {
  ::v-deep .v-input__control {
    width: 24px;
    height: 24px;
    .v-input--selection-controls__ripple {
      display: none;
    }
  }
}
.top-list {
  position: relative;
  padding: 10px 0 10px 30px;
  margin-top: 10px;
  &:first-child {
    margin-top: 0;
  }
  div {
    &:nth-child(-n + 3) {
      margin-bottom: 6px;
    }
  }
  input {
    border: 1px solid #949494;
    border-radius: 5px;
  }
  .v-input--checkbox {
    position: absolute;
    top: 14px;
    left: 4px;
    margin: 0;
    width: 24px;
    height: 24px;
  }
}
</style>

<style lang="sass" scoped>
.scanContainer
  >.row
    margin: 0
    padding: 10px

  .PackingMarking_table
    ::v-deep .v-data-table__mobile-table-row
      margin: 4px 8px
      background-color: #e8e8e8f1
    ::v-deep .v-data-table__mobile-row
      min-height: 28px !important
      // 暂无数据的显示
      ::v-deep .v-data-table__empty-wrapper
        display: flex
        justify-content: center
        align-items: center
        td
          line-height: 48px

  .inputPlaceholder
    ::v-deep.v-text-field__slot
      input::-webkit-input-placeholder
        font-size: 15px
      input::-moz-placeholder
        font-size: 15px
      input:-moz-placeholder
        font-size: 15px
      input:-ms-input-placeholder
        font-size: 15px
</style>
